package com.swh.controller;

import com.swh.entity.Dept;
import com.swh.entity.PageEntity;
import com.swh.entity.User;
import com.swh.servic.DeptService;
import com.swh.servic.UserServic;
import com.swh.utils.FileUploadUtils;
import com.swh.utils.XBUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: swh
 * @Description:
 * @Date: 2020/11/23 12:04
 * @Version: 1.0
 */
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserServic userServic = new UserServic();
    private DeptService deptService = new DeptService();

    //登录模块
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        String remember = request.getParameter("remember");
        String remember2 = request.getParameter("remember2");

        String sessionCode = (String) session.getAttribute("sessionCode");

        //判断验证码是否正确
        if (!sessionCode.equals(checkCode)) {
            request.setAttribute("error", "验证码错误");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        //判断用户名是否正确
        User user = userServic.findByUserName(username);

        if (user == null) {
            request.setAttribute("error", "用户名错误");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        //判断密码是否正确
        if (!user.getPassword().equals(password)) {
            request.setAttribute("error", "密码错误");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        //免登录
        // 更改用户登录时间
//        userServic.updateLoginTime(user.getId());
        if ("1".equals(remember)) {
            // 用户勾选了 '记住我'
            Cookie cookie = new Cookie("login", user.getId() + "");

            // 设置cookie携带路径(整体项目都携带)
            cookie.setPath("/");

            // cookie过期时间
            cookie.setMaxAge(60 * 60 * 24 * 7);

            // 写回客户端
            response.addCookie(cookie);
        }

        if(!"2".equals(remember2)){
            //说明勾选了第三方协议
            request.setAttribute("error", "你还没详细阅读并同意");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        //修改用户的登录时间
        userServic.updateLoginTime(user.getId());

        //登录成功
        session.setAttribute("login", user);

        response.sendRedirect("/html/home.jsp");

    }

    //微信登录//发起二维码页面
    public void wx_login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Properties prop = new Properties();
        prop.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));

        String appid = prop.getProperty("wx.AppID");

        String redirectUri = prop.getProperty("wx.redirect_uri");

        String url="https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=" +appid+
                "&redirect_uri=" +redirectUri+
                "&response_type=code" +
                "&scope=snsapi_login"  ;

        response.sendRedirect(url);

    }

    //QQ登录//发起二维码页面
    public void qq_login(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Properties prop=new Properties();
        prop.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));

        String appid = prop.getProperty("qq.AppID");

        //QQ互联中的回调地址
        String redirect_uri = prop.getProperty("qq.redirect_uri");

        //Step1：获取Authorization Code
        String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code"+
                "&client_id=" + appid +
                "&redirect_uri=" + URLEncoder.encode(redirect_uri) +
                "&state=1" ;

        // 重定向到QQ登录指定的地址进行QQ授权,授权成功后返回code
        response.sendRedirect(url);
    }

    //注销
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        // 清除session
        request.getSession().removeAttribute("login");

        Cookie loginCookie = XBUtils.getCookie(request, "login");

        if (loginCookie != null) {

            // 销毁cookie
            loginCookie.setPath("/");
            loginCookie.setMaxAge(0);
            response.addCookie(loginCookie);
        }

        response.sendRedirect("/index.jsp");
    }

    //注册成功
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();

        User user = new User();

        try {
//            BeanUtils.populate(user,parameterMap);
            BeanUtils.populate(user, getParam(request));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        userServic.register(user);
        response.sendRedirect("/index.jsp");

    }

    //判断用户名是否存在
    public void checkUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");

        User user = userServic.findByUserName(username);

        response.setContentType("text/html;charset=UTF-8");

        if (user == null) {
//            response.getWriter().write("0");
            writeObjToString(response, "0");
            return;
        } else {
//            response.getWriter().write("1");
            writeObjToString(response, "1");
        }
    }

    //注册邮箱是否存在
    public void checkEmail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String email = request.getParameter("email");

        User user = userServic.findByEmail(email);

        response.setContentType("text/html;charset=UTF-8");

        if (user == null) {
            response.getWriter().write("0");
            return;
        }
        response.getWriter().write("1");

    }

    //查询所有
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Map<String, String> param = getParam(request);

        String realName = param.get("realName");

        //查询所有
//        List<User> userList = userServic.findAll();

        //查询所有带添加查询
        List<User> userList = userServic.search(realName);

        request.setAttribute("userList", userList);
        request.setAttribute("realName", realName);

        request.getRequestDispatcher("/html/user.jsp").forward(request, response);


    }

    //查询所有带添加+分页
    public void findPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String> param = getParam(request);

        // 搜索条件
        String realName = param.get("realName");

        // 当前页
        Integer currPage = Integer.parseInt(param.get("currPage"));

        // 包含了整个页面的数据
        PageEntity<User> pageEntity = userServic.findPage(realName, currPage);

        request.setAttribute("pageData", pageEntity);
        request.setAttribute("realName", realName);

        //查看关注那些人
        List<Long> focusList = userServic.findFocusListByUserId(login.getId());

        request.setAttribute("focusList", focusList);

        request.getRequestDispatcher("/html/user.jsp").forward(request, response);

    }

    public void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Map<String, String> param = getParam(request);

        String flag = param.get("flag");

        Long id = Long.parseLong(param.get("id"));

        User user = userServic.findById(id);

        if ("detail".equals(flag)) {
            //查看别人的信息
            //查看数
            userServic.incLook(id);

            //查看数 //查询粉丝数
            Integer fans = userServic.findFans(id);

            request.setAttribute("user", user);
            request.setAttribute("fans", fans);

            request.getRequestDispatcher("/html/user_detail.jsp").forward(request, response);
            return;
        }
        //查看自己的信息

        //关注数
        Integer focus = userServic.findFocus(id);

        //查看所有部门
        List<Map<String, Object>> deptMapList = deptService.findAll();

        request.setAttribute("user", user);
        request.setAttribute("focus", focus);
        request.setAttribute("deptMapList", deptMapList);


        request.getRequestDispatcher("/html/user_look.jsp").forward(request, response);
    }

    //图片上传
    public void updatePic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 上传到服务器最新的图片路径
        String path = FileUploadUtils.upload("/upload", request);

        // 更新数据库中的地址
        userServic.updatePic(login.getId(), path);

        writeObjToString(response, path);

    }

    //修改
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Map<String, String> param = getParam(request);

        User user = new User();

        try {
            BeanUtils.populate(user, param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        User dbUser = userServic.findById(user.getId());

        user.setPic(dbUser.getPic());
        user.setLook(dbUser.getLook());
        user.setPassword(dbUser.getPassword());
        user.setEmail(dbUser.getEmail());

        Dept dept = deptService.findById(user.getDeptId());
        user.setDeptName(dept.getName());

        if (user.getIsSecret() == null) {
            user.setIsSecret("1");
        }

        userServic.update(user);

        request.getSession().setAttribute("login", user);

//        request.getRequestDispatcher("/user/detail?id=" + user.getId()).forward(request, response);
        response.sendRedirect("/user/detail?id=" + user.getId());

    }

    //加关注或取消关注
    public void focus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String> param = getParam(request);

        long userId = Long.parseLong(param.get("userId"));

        Integer flag = userServic.focus(login.getId(), userId);

        writeObjToString(response, flag);
    }

    //我的关注列表+分页
    public void findFocusPage(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, String> param = getParam(request);
        Integer currPage = Integer.parseInt(param.get("currPage"));

        PageEntity<Map<String, Object>> pageEntity = userServic.findFocusPage(login.getId(), currPage);

        request.setAttribute("pageData", pageEntity);
        request.setAttribute("currPage", currPage);

        request.getRequestDispatcher("/html/my_user.jsp").forward(request, response);

    }

    public void findUserByDeptId(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Long deptId = Long.parseLong(getParam(request).get("deptId"));

        List<Map<String, Object>> userMapList = userServic.findUserByDeptId(deptId);

        writeObjToString(response, userMapList);
    }

}
